﻿using Fonour.Application.Dtos;
using Fonour.Application.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Fonour.MVC.Controllers
{
    public class UserController : FonourControllerBase
    {
        private readonly IUserAppService _userAppService;
        private readonly IRoleService _roleService;

        public UserController(IUserAppService userAppService, IRoleService roleService)
        {
            this._userAppService = userAppService;
            _roleService = roleService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> GetUserByDepartmentAsync(Guid departmentId, int startPage, int pageSize)
        {
            var result = await this._userAppService.GetPageListAsync(startPage, pageSize, p => p.DepartmentId == departmentId, p => p.CreateTime);
            var roles = await this._roleService.GetAllListAsync(p => p.Code);
            return Json(new
            {
                rowCount = result.TotalCount,
                pageCount = Math.Ceiling(Convert.ToDecimal(result.TotalCount) / pageSize),
                rows = result.DataList,
                roles = roles
            });
        }

        public IActionResult Edit(UserDto dto, string roles)
        {
            try
            {
                if (dto.Id == Guid.Empty)
                {
                    dto.Id = Guid.NewGuid();
                    dto.CreateTime = DateTime.Now;

                    string userId = string.Empty;
                    var loginUser = HttpContext.User;
                    if (loginUser.Claims.Any(p => p.Type == ClaimTypes.Sid))
                    {
                        userId = loginUser.Claims.FirstOrDefault(p => p.Type == ClaimTypes.Sid).Value;
                    }

                    dto.CreateUserId = Guid.Parse(userId);
                }

                var userRoles = new List<UserRoleDto>();
                foreach (var role in roles.Split(','))
                {
                    userRoles.Add(new UserRoleDto() { UserId = dto.Id, RoleId = Guid.Parse(role) });
                }

                dto.UserRoles = userRoles;
                var user = this._userAppService.InsertOrUpdate(dto);
                return Json(new { Result = "Success" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "Faild", Message = ex.Message });

            }
        }

        public IActionResult DeleteMuti(string ids)
        {
            try
            {
                string[] idArray = ids.Split(',');
                List<Guid> delIds = new List<Guid>();
                foreach (string id in idArray)
                {
                    delIds.Add(Guid.Parse(id));
                }
                
                this._userAppService.DeleteBatch(delIds);
                return Json(new
                {
                    Result = "Success"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    Result = "Faild",
                    Message = ex.Message
                });
            }
        }
        public IActionResult Delete(Guid id)
        {
            try
            {
                this._userAppService.Delete(id);
                return Json(new
                {
                    Result = "Success"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    Result = "Faild",
                    Message = ex.Message
                });
            }
        }
        public async Task<IActionResult> GetAsync(Guid id)
        {
            var dto = await this._userAppService.GetWithRolesAsync(id);
            return Json(dto);
        }
    }
}
